package devkit.commando.http {
	
	import devkit.commando.CommandBase;
	import devkit.commando.CommandManager;
	import devkit.commando.ICommand;
	
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	
	/**
	 * Base HTTP command class that should be extended by all HTTP command classes.
	 * @author Francois Dempers
	 */
	public class HTTPBase extends CommandBase {
		
		/** The URL to connect to. */
		private var serviceURL:String;
		
		/** The connection method to use, for example GET, POST, PUT, DELETE, etc. */
		private var serviceMethod:String;
		
		/**
		 * Creates a new <code>HTTPBase</code> command.
		 * @param url The URL to connect to.
		 * @param method The connection method to use, for example GET, POST, PUT, DELETE, etc.
		 * @param resultHandler The client side function to invoke when a result is received.
		 * @param faultHandler The client side function to invoke when a fault is received.
		 */
		public function HTTPBase(url:String, method:String, resultHandler:Function=null, faultHandler:Function=null) {
			
			super(resultHandler, faultHandler);
			serviceURL = url;
			serviceMethod = method;
		}
		
		/**
		 * Invokes the server side function of the command.
		 * @param args The arguments to pass to the server side script.
		 */
		protected function invoke(args:Object=null):void {
			
			var service:HTTPService = new HTTPService();
			service.url = serviceURL;
			service.method = serviceMethod;
			
			if(service.hasEventListener(ResultEvent.RESULT) == false) {
				service.addEventListener(ResultEvent.RESULT, (this as ICommand).result, false, 0, true);
			}
			if(service.hasEventListener(FaultEvent.FAULT) == false) {
				service.addEventListener(FaultEvent.FAULT, (this as ICommand).fault, false, 0, true);				
			}
			service.send(args);
			
			CommandManager.processChain.addCommand(this);
		}
	}
}